<?php

namespace app\admin\model;

use think\facade\Db;

class SupplierBalanceWarningConfig
{
    private $table = 'supplier_balance_warning_config';

    /**
     * 列表.
     */
    public function getList($params)
    {
        $where = [];
        if (!empty($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }
        if (!empty($params['serv_type'])) {
            $where[] = ['serv_type', '=', $params['serv_type']];
        }
        $paginate = [
            'page' => $params['page'] ?? 1,
            'list_rows' => $params['list_rows'] ?? 10,
        ];
        $list = Db::name($this->table)
            ->where($where)
            ->order('id desc')
            ->paginate($paginate)
            ->toArray();
        $mobileSupplier = Db::name('mobile_supplier')
            // ->where('is_deleted', 0)
            ->column('name', 'id');
        $baseSupplier = Db::name('base_supplier')
            // ->whereNull('deleted_at')
            ->column('name', 'id');

        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['mobile'] = json_decode($v['mobile'], true);
            $list['data'][$k]['uniqueId'] = $v['supplier_id'] . '-' . $v['serv_type'];
            $list['data'][$k]['serv_name'] = PRODUCT_SERV_TYPE[$v['serv_type']]['name'];
            if ($v['serv_type'] == PRODUCT_MOBILE_SERV) {
                $list['data'][$k]['supplier_name'] = $mobileSupplier[$v['supplier_id']] ?? '';
            } else {
                $list['data'][$k]['supplier_name'] = $baseSupplier[$v['supplier_id']] ?? '';
            }
        }

        return success('操作成功', $list);
    }

    /**
     * 添加.
     */
    public function save($params)
    {
        $id = 0;
        if (!empty($params['id'])) {
            $id = Db::name($this->table)
                ->where('id', $params['id'])
                ->value('id');
        }
        // uniqueId == $supplier_id . '-' . $serv_type
        list($params['supplier_id'], $params['serv_type']) = explode('-', $params['uniqueId']);
        $unique = Db::name('supplier_balance_warning_config')
            ->where('supplier_id', $params['supplier_id'])
            ->where('serv_type', $params['serv_type'])
            ->where('id', '<>', $id)
            ->value('id');
        if ($unique) {
            return fail('该供应商已经添加过');
        }
        if (!isset(PRODUCT_SERV_TYPE[$params['serv_type']])) {
            return fail('供应商类型有误');
        }

        // 判断供应商是否存在
        if ($params['serv_type'] == PRODUCT_MOBILE_SERV) {
            $supplierExists = Db::name('mobile_supplier')
                ->where('id', $params['supplier_id'])
                ->where('is_deleted', 0)
                ->value('id');
        } else {
            $supplierExists = Db::name('base_supplier')
                ->where('id', $params['supplier_id'])
                ->whereNull('deleted_at')
                ->value('id');
        }
        if (!$supplierExists) {
            return fail('供应商不存在');
        }

        if (empty($params['mobile']) || !is_array($params['mobile'])) {
            return fail('请填写预警号码');
        }
        $mobile = [];
        foreach ($params['mobile'] as $v) {
            $v = trim($v);
            if (empty($v)) {
                continue;
            }
            if (!checkMobile($v)) {
                return fail('手机号码【' . $v . '】格式有误');
            }
            $mobile[] = $v;
        }
        $mobile = array_unique($mobile);
        $data = [
            'supplier_id' => $params['supplier_id'],
            'serv_type' => $params['serv_type'],
            'status' => $params['status'],
            'balance' => $params['balance'],
            'mobile' => json_encode($mobile),
        ];

        Db::startTrans();
        try {
            if ($id) {
                Db::name($this->table)
                    ->where('id', $id)
                    ->update($data);
            } else {
                Db::name($this->table)
                    ->insert($data);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('保存失败：' . $e->getMessage());
        }

        return success('保存成功');
    }

    /**
     * 修改状态
     */
    public function changeStatus($params)
    {
        $info = Db::name($this->table)
            ->field('id, status')
            ->where('id', $params['id'])
            ->find();
        if (empty($info)) {
            return fail('记录不存在');
        }
        if ($info['status'] == $params['status']) {
            return fail('修改成功');
        }

        Db::startTrans();
        try {
            Db::name($this->table)
                ->where('id', $params['id'])
                ->update([
                    'status' => $params['status'],
                ]);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('修改失败：' . $e->getMessage());
        }

        return success('修改成功');
    }

    /**
     * 删除.
     */
    public function delete($params)
    {
        if (empty($params['id'])) {
            return fail('参数有误');
        }
        $info = Db::name($this->table)
            ->where('id', $params['id'])
            ->find();
        if (empty($info)) {
            return success('删除成功');
        }

        Db::startTrans();
        try {
            Db::name($this->table)
                ->where('id', $info['id'])
                ->delete();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('删除失败: ' . $e->getMessage());
        }

        return success('删除成功');
    }

    /**
     * 供应商列表：话费【mobile_supplier】 + 其他供应商【base_supplier】
     */
    public static function getSupplierList()
    {
        $mobileSupplier = Db::name('mobile_supplier')
            ->field('id, name, 1 as serv_type, balance')
            ->where('is_deleted', 0)
            ->where('is_main', 1)
            ->select()
            ->toArray();
        $baseSupplier = Db::name('base_supplier')
            ->field('id, name, serv_type, balance')
            ->whereNull('deleted_at')
            ->select()
            ->toArray();
        $supplier = array_merge($mobileSupplier, $baseSupplier);
        unset($mobileSupplier);
        unset($baseSupplier);
        foreach ($supplier as $k => $v) {
            // 过滤滴滴加油
            if ($v['serv_type'] == PRODUCT_OIL_SERV) {
                unset($supplier[$k]);
                continue;
            }
            if (empty($v['serv_type'])){
                continue;
            }
            $supplier[$k]['name'] = PRODUCT_SERV_TYPE[$v['serv_type']]['name'] . '-' . $v['name'];
            $supplier[$k]['uniqueId'] = $v['id'] . '-' . $v['serv_type'];
        }
        return $supplier;
    }
}
